package com.undsf.ezhttp;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * Created by Arathi on 2017/4/6.
 */
public abstract class FileUtils {
    public static boolean Exists(String path) {
        File file = new File(path);
        return file.exists();
    }

    public static byte[] Read(File file) {
        if (!file.exists()) return null;

        int fileLength = (int) file.length();
        byte[] binaryContent = new byte[fileLength];
        try {
            FileInputStream inStream = new FileInputStream(file);
            int readLength = inStream.read(binaryContent, 0, fileLength);
            if (readLength != fileLength) {
                // TODO 长度不符
            }
            inStream.close();
            return binaryContent;
        }
        catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static String Read(File file, Charset charset) {
        if (!file.exists()) return null;

        byte[] binaryContent = Read(file);
        String content = new String(binaryContent, charset);
        return content;
    }

    public static boolean Write(File file, byte[] data) {
        try {
            FileOutputStream outStream = new FileOutputStream(file);
            outStream.write(data, 0, data.length);
            outStream.flush();
            outStream.close();
            return true;
        }
        catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
        return false;
    }

    public static boolean Write(File file, String content, Charset charset) {
        byte[] data = content.getBytes(charset);
        return Write(file, data);
    }
}
